package com.xin.bi.mq;

import com.google.gson.Gson;
import com.rabbitmq.client.Channel;
import com.xin.bi.constant.MqConstant;
import com.xin.bi.exception.BusinessException;
import com.xin.bi.manager.AiManager;
import com.xin.bi.model.dto.chart.GenChartByAiRequest;
import com.xin.bi.model.entity.Chart;
import com.xin.bi.service.ChartService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.BeanUtils;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Component
@Slf4j
public class BiMessageComsumer {
    @Resource
    private ChartService chartService;
    @Resource
    private AiManager aiManager;

    @SneakyThrows
    @RabbitListener(queues = MqConstant.BI_QUEUE_NAME,ackMode = "MANUAL")
    public void  receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {
        if (StringUtils.isBlank(message)){
            channel.basicNack(deliveryTag,false,false);
            throw new BusinessException("消息id有误");
        }
        long charId = Long.parseLong(message);
        Chart chart = chartService.getById(charId);
        if (chart==null){
            throw new BusinessException("没有该图表");
        }
        GenChartByAiRequest genChartByAiRequest = new GenChartByAiRequest();
        BeanUtils.copyProperties(chart,genChartByAiRequest);
        Gson gson = new Gson();
        String genChartByAiRequestJson = gson.toJson(genChartByAiRequest, GenChartByAiRequest.class);
        String sendAiMessage = chartService.jointSendAiMessage(genChartByAiRequestJson, chart.getChartData());
        chartService.genChartAsync(charId,sendAiMessage);
        channel.basicAck(deliveryTag, false);
    }
}
